package com.pointcircle.core.web.auth;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.pointcircle.core.FrameworkConstant;
import com.pointcircle.core.entity.User;
import com.pointcircle.core.repository.UserRepository;
import com.pointcircle.core.service.PropertyService;
import com.pointcircle.core.util.JwtUtils;
import com.pointcircle.core.util.RestResponseUtils;
import com.pointcircle.core.web.RestResponse;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("auth/status")
@Slf4j
public class StatusApi {
	@Autowired
	private PropertyService propertyService;
	
	@Autowired
	private UserRepository userRepository;
	
	@RequestMapping("jwt")
	public RestResponse login(@RequestParam("jwtToken") String jwtToken) {
		try {
			if(StringUtils.isEmpty(jwtToken)) {
				throw new AuthenticationException(
					propertyService.getProperty("pointcircle.framework.message.auth.token-invalid")
				);
			}
			String userId = JwtUtils.getUserId(jwtToken);
			if(userId == null) {
				throw new AuthenticationException(
					propertyService.getProperty("pointcircle.framework.message.auth.token-invalid")
				);
			}
			User user = userRepository.findOne(userId);
			if(user == null) {
				throw new AuthenticationException(
					propertyService.getProperty("pointcircle.framework.message.auth.user-not-exist")
				);
			}
			RestResponseAuthInfo res = new RestResponseAuthInfo(jwtToken, user);
			return res;
		} catch(Exception e) {
			log.error(e.getMessage(), e);
			RestResponse res = RestResponseUtils.fail(FrameworkConstant.ERROR_CODE_LOGIN_STATUS_FAIL, e.getMessage());
			return res;
		}
	}
}
